import 'package:amap_flutter_map/amap_flutter_map.dart';
import 'package:amap_flutter_base/amap_flutter_base.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/src/foundation/diagnostics.dart';
import 'package:get/get.dart';
import 'package:amap_flutter_location/amap_flutter_location.dart';
import 'package:amap_flutter_location/amap_location_option.dart';
import 'package:yinshui_caiying/services/location_services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:common_utils/common_utils.dart';

class MapDialog extends StatefulWidget {
  MapDialog() : super();

  @override
  _MapDialogState createState() => _MapDialogState();
}

class _MapDialogState extends State<MapDialog> {
  ///获取地图服务
  LocationService locationService = Get.find();

  ///创建地图中心点
  late LatLng mapCenter = LatLng(locationService.locationResult.value.latitude,
      locationService.locationResult.value.longitude);

  ///创建气泡标题
  late String title = '当前位置';

  ///创建标记
  late Marker marker = Marker(
      position: mapCenter,
      clickable: true,
      draggable: true,
      icon: BitmapDescriptor.defaultMarkerWithHue(BitmapDescriptor.hueGreen),
      infoWindow: InfoWindow(title: title),
      onTap: onMakerTap,
      onDragEnd: onMakerDragEnd);

  ///创建标记集合
  Map<String, Marker> _initMarkerMap = <String, Marker>{};

  ///创建地图控制器
  late final AMapController _mapController;

  ///地图创建完成回调,成功后会返回AMapController对象
  void onMapCreated(AMapController controller) {
    setState(() {
      _mapController = controller;
      _initMarkerMap[marker.id] = marker;
    });

    _mapController.moveCamera(
        CameraUpdate.newCameraPosition(
          CameraPosition(
              //中心点
              target: mapCenter,
              //缩放级别
              zoom: 18,
              //俯仰角0°~45°（垂直与地图时为0）
              tilt: 30,
              //偏航角 0~360° (正北方为0)
              bearing: 0),
        ),
        animated: true,
        duration: 250);
  }

  ///位置变化回调
  void onLocationChanged(AMapLocation location) {
    if (null == location) {
      return;
    }
    // print('_onLocationChanged ${location.toJson()}');
  }

  ///地图移动回调
  void onCameraMove(CameraPosition cameraPosition) {
    if (null == cameraPosition) {
      return;
    }
    // print('onCameraMove===> ${cameraPosition.toMap()}');
  }

  ///地图移动结束回调
  void onCameraMoveEnd(CameraPosition cameraPosition) {
    if (null == cameraPosition) {
      return;
    }
    // print('_onCameraMoveEnd===> ${cameraPosition.toMap()}');
  }

  ///点击地图回调
  void onMapTap(LatLng latLng) {
    if (null == latLng) {
      return;
    }
    print('点击地图===> ${latLng.toJson()}');
    locationService.locationResult.update((val) {
      val!.latitude =
          NumUtil.getNumByValueDouble(latLng.latitude, 6)!.toDouble();
      val.longitude =
          NumUtil.getNumByValueDouble(latLng.longitude, 6)!.toDouble();
    });
    setState(() {
      _initMarkerMap[marker.id] = marker.copyWith(positionParam: latLng);

      // _initMarkerMap.clear();
    });
  }

  ///长按回调
  void onMapLongPress(LatLng latLng) {
    if (null == latLng) {
      return;
    }
    print('_onMapLongPress===> ${latLng.toJson()}');
  }

  ///pio点击回调
  void onMapPoiTouched(AMapPoi poi) {
    if (null == poi) {
      return;
    }
    print('_onMapPoiTouched===> ${poi.toJson()}');
  }

  ///maker点击回调
  void onMakerTap(String id) {
    print('点击标记===> ${id}');
  }

  ///拖拽结束
  void onMakerDragEnd(String id, LatLng latLng) {
    print(latLng);
  }

  ///重新定位
  void onResetLoacation() {
    locationService.startLocation();
    setState(() {
      _initMarkerMap[marker.id] = marker.copyWith(positionParam: mapCenter);
    });

    _mapController.moveCamera(
        CameraUpdate.newCameraPosition(
          CameraPosition(
              //中心点
              target: mapCenter,
              //缩放级别
              zoom: 18,
              //俯仰角0°~45°（垂直与地图时为0）
              tilt: 30,
              //偏航角 0~360° (正北方为0)
              bearing: 0),
        ),
        animated: true,
        duration: 250);
  }

  /// 获取审图号
  void getApprovalNumber() async {
    //普通地图审图号
    String mapContentApprovalNumber =
        (await _mapController.getMapContentApprovalNumber());
    //卫星地图审图号
    String satelliteImageApprovalNumber =
        (await _mapController.getSatelliteImageApprovalNumber());

    print('地图审图号（普通地图）: $mapContentApprovalNumber');
    print('地图审图号（卫星地图): $satelliteImageApprovalNumber');
  }

  @override
  Widget build(BuildContext context) {
    ///创建地图实例
    final AMapWidget map = AMapWidget(

        ///是否显示3D建筑物
        buildingsEnabled: true,

        ///是否指南针
        compassEnabled: true,

        ///比例尺是否显示
        scaleEnabled: true,

        ///是否显示路况图层
        trafficEnabled: true,

        ///是否显示底图文字
        labelsEnabled: true,
        markers: Set<Marker>.of(_initMarkerMap.values),
        onMapCreated: onMapCreated,
        onCameraMove: onCameraMove,
        onCameraMoveEnd: onCameraMoveEnd,
        onLocationChanged: onLocationChanged,
        onTap: onMapTap,
        onLongPress: onMapLongPress,
        onPoiTouched: onMapPoiTouched);
    return Container(
      width: 0.9.sw,
      height: 0.6.sh,
      child: Stack(
        children: [
          Container(
            child: map,
          ),
          Align(
            alignment: Alignment.bottomRight,
            child: IconButton(
                icon: Icon(Icons.location_searching),
                onPressed: () {
                  onResetLoacation();
                }),
          )
        ],
      ),
    );
  }
}
